package com.demo.controller;

import com.demo.myconst.MyConst;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 写三个方法：show down toUTF8String
 */
@Controller
public class FileDownController {
    private static final Log logger = LogFactory.getLog(FileDownController.class);

    /**
     * 显示要下载的文件
     */
    @RequestMapping("/showDownFiles")
    public String show(HttpServletRequest request, Model model) {
        //要从D盘upload下载
        String realPath = MyConst.UPLOAD_PATH;
        File dir = new File(realPath);
        File[] files = dir.listFiles();
        //获取该目录下的所有文件名
        List<String> fileName = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            fileName.add(files[i].getName());
        }
        model.addAttribute("files", fileName);
        return "showDownFiles";
    }

    /**
     * 执行下载
     */
    @RequestMapping("/down")
    public String down(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response) {
        //要下载的文件路径
        String aFilePath = null;
        //输入流
        FileInputStream in = null;
        //输出流
        ServletOutputStream out = null;
        try {
            aFilePath = MyConst.UPLOAD_PATH;
            //设置下载文件使用的报头
            response.setHeader("Content-Type", "application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=" + toUTF8String(filename));
            //读入文件
            in = new FileInputStream(aFilePath + "\\" + filename);
            //得到响应对象的输出流，用于向客户端输出二进制数据
            out = response.getOutputStream();
            out.flush();
            int aRead = 0;
            byte[] b = new byte[1024];
            while ((aRead = in.read(b)) != -1 & in != null) {
                out.write(b, 0, aRead);
            }
            out.flush();
            in.close();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("下载成功！");
        return null;
    }

    /**
     * 下载保存时 中文文件名字符编码转换方法
     */
    public String toUTF8String(String str) {
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            //取出字符串中的每一个字符
            char c = str.charAt(i);
            //Unicode码值 在0-255 不作处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                //将Unicode编码 转换为UTF-8编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    b = null;
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        //按位与操作，将两边的数字 转成二进制
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
}
